package com.xxkj.nmip.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.Toast;

import com.tencent.smtt.sdk.MimeTypeMap;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadNativeTask extends AsyncTask<String, Void, String> {

    private Context context;
    private String cookieStr = "";
    // 传递两个参数：URL 和 目标路径
    private String url;
    private String fileName;
    public DownloadNativeTask(Context context,String cookieStr) {
        this.context = context;
        this.cookieStr = cookieStr;
    }

    @Override
    protected String doInBackground(String... params) {

         url = params[0]; // 要访问的链接
         fileName = params[1]; // 文件名

        if (TextUtils.isEmpty(url)) {
            return null;
        }

        File directory = Environment.getExternalStorageDirectory();
        File file = new File(directory, fileName);
        if (file.exists()) {
            return fileName;
        }

        // 下载文件
        try {
            URL myFileUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) myFileUrl
                    .openConnection();
            // 携带cookie请求，要写在请求开始之前
            conn.addRequestProperty("Cookie", cookieStr);
            conn.setDoInput(true);
            conn.connect();

            InputStream is = conn.getInputStream();
            // 我们把文件保存在sd卡根目录
            FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +fileName);
            byte[] buffer = new byte[1024];
            int r;
            while ((r = is.read(buffer)) > 0) {
                out.write(buffer, 0, r);
                out.flush();
            }
            is.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return fileName;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Toast.makeText(context,"下载成功,存储地址:"+fileName,Toast.LENGTH_SHORT).show();
        // 这里可以对下载好的文件进行打开等操作
//        Intent handlerIntent = new Intent(Intent.ACTION_VIEW);
//        String mimeType = getMIMEType(url);
//        Uri uri = Uri.fromFile(new File(fileName));
//        handlerIntent.setDataAndType(uri, mimeType);
//        context.startActivity(handlerIntent);

    }

    @Override
    protected void onProgressUpdate(Void... values) {

    }


    private String getMIMEType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return type;
    }
}